package band.wukong.practice.netty.nettyinactionessential.ch02;

import band.wukong.practice.netty.Env;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.net.InetSocketAddress;

/**
 * Desc:
 * author: wukonggg@139.com
 */
public class EchoClient {

    private static final Logger logger;

    static {
        Env.assemblingLog4j2ConfFile();
        logger = LogManager.getLogger(EchoServer.class);
    }

    private final String HOST;
    private final int PORT;

    public EchoClient(String host, int port) {
        HOST = host;
        PORT = port;
    }

    public void start() throws InterruptedException {
        EventLoopGroup group = new NioEventLoopGroup();

        try {
            Bootstrap b = new Bootstrap();  // 1.创建 Bootstrap

            // 2.指定 EventLoopGroup 来处理客户端事件。
            //   由于我们使用 NIO 传输，所以用到了 NioEventLoopGroup 的实现
            b.group(group)
                    .channel(NioSocketChannel.class)    // 3.使用的 channel 类型是一个用于 NIO 传输
                    .remoteAddress(new InetSocketAddress(HOST, PORT))   // 4.设置服务器的 InetSocketAddress
                    .handler(
                            // 5.当建立一个连接和一个新的通道时，
                            //   创建添加到 EchoClientHandler 实例到 channel pipeline
                            new ChannelInitializer<SocketChannel>() {
                                @Override
                                protected void initChannel(SocketChannel ch) throws Exception {
                                    ch.pipeline().addLast(new EchoClientHandler());
                                }
                            });
            ChannelFuture f = b.connect().sync();   // 6.连接到远程;等待连接完成
            f.channel().closeFuture().sync();   // 7.阻塞直到 Channel 关闭
        } finally {
            group.shutdownGracefully().sync();  // 8.调用 shutdownGracefully() 来关闭线程池和释放所有资源
        }
    }

}
